package com.base.core.util;

import com.base.core.error.ErrorUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Function;


public class TypeUtils {
	private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Function<String, Object> fromString(Class<?> type) {
		if (type.equals(String.class)||type.equals(String[].class))
			return String::valueOf;
		if (type.equals(Integer.TYPE))
			return Integer::valueOf;
		if (type.equals(Integer.class))
			return Integer::parseInt;
		if (type.equals(Long.TYPE))
			return Long::valueOf;
		if (type.equals(Long.class))
			return Long::parseLong;
		if (type.equals(Boolean.TYPE))
			return Boolean::valueOf;
		if (type.equals(Boolean.class))
			return Boolean::parseBoolean;
		 if (type.isEnum())
		 return (s) -> {
			 Class cls=type;
			return Enum.valueOf(cls, s);
		 };
		if (type.equals(Date.class))
			return (s) -> {
				try {
					return dateFormat.parse(s);
				} catch (ParseException e) {
					throw ErrorUtils.wrap(e);
				}
			};
		if (type.equals(Float.TYPE))
			return Float::valueOf;
		if (type.equals(Float.class))
			return Float::parseFloat;
		if (type.equals(Double.TYPE))
			return Double::valueOf;
		if (type.equals(Double.class))
			return Double::parseDouble;
		return null;
	}
}
